package com.yuyou.fn.tradingservice.service.impl;

import com.github.wens.framework.service.impl.SuperServiceImpl;
import com.github.wens.mybatisplus.examples.Example;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.BeanUtils;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.platform.entity.SysUser;
import com.yuyou.fn.tradingservice.entity.PersonLeaseMessage;
import com.yuyou.fn.tradingservice.entity.ServiceProduct;
import com.yuyou.fn.tradingservice.entity.ServiceProductListing;
import com.yuyou.fn.tradingservice.mapper.ServiceProductListingMapper;
import com.yuyou.fn.tradingservice.service.ILeaseMessageService;
import com.yuyou.fn.tradingservice.service.IPersonLeaseMessageService;
import com.yuyou.fn.tradingservice.service.IServiceProductListingService;
import com.yuyou.fn.tradingservice.service.IServiceProductService;
import com.yuyou.fn.tradingservice.vo.ListingDetailVo;
import com.yuyou.fn.tradingservice.vo.PersonLeaseQueryVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 *
 * ServiceProductListing 表数据服务层接口实现类
 *
 */
@Service
public class ServiceProductListingServiceImpl extends SuperServiceImpl<ServiceProductListingMapper, ServiceProductListing,Long> implements IServiceProductListingService {
    @Resource
    private IPersonLeaseMessageService personLeaseMessageService;

    @Resource
    private IServiceProductService serviceProductService;

    @Resource
    private ILeaseMessageService leaseMessageService;

    @Override
    public Long addGoodToListing(SysUser user, Long  productId,int quantity,Integer createOrAdd) {
        ServiceProduct serviceProduct = serviceProductService.findById(productId);
        if ( quantity <= 0) {
            throw new BusException("添加的数量不可小于0");
        }

        if (serviceProduct == null || serviceProduct.getStatus() == 0) {
            throw new BusException("商品不存在或者已下架");
        }
    /*    if (serviceProduct.getSellerId().equals(user.getUserId())){
            throw new BusException("不可购买自己发布的商品");
        }*/


        if (serviceProduct.getInventory()<quantity){
            throw new BusException("商品的库存小于添加的数量");
        }

        /*有效的购物车*/
        ServiceProductListing serviceProductListingVo=this.findByBuyIdAndProduct(user.getUserId(),serviceProduct.getProductId());
        if (serviceProductListingVo==null || createOrAdd==0){
            ServiceProductListing serviceProductListing =new ServiceProductListing();
            BeanUtils.copyProperties(serviceProductListing,serviceProduct);
            serviceProductListing.setBuyerId(user.getUserId());
            serviceProductListing.setBuyerName(user.getUsername());
            serviceProductListing.setBuyerPhoneNo(user.getPhoneNo());
            serviceProductListing.setQuantity(quantity);
            serviceProductListing.setTotalPrice(serviceProduct.getUnitPrice().multiply(new BigDecimal(quantity)));
            serviceProductListing.setEffectiveness(1);
            this.insert(serviceProductListing);
            return  serviceProductListing.getListingId();
        }else {
            Integer realQuantity=serviceProductListingVo.getQuantity()+quantity;
            if (realQuantity>serviceProduct.getInventory()){
                throw new BusException("添加到购物车的数量已超出库存");
            }
            ServiceProductListing update=new ServiceProductListing();
            update.setUpdateTime(TimeUtils.now());
            update.setListingId(serviceProductListingVo.getListingId());
            update.setQuantity(realQuantity);
            update.setTotalPrice(serviceProductListingVo.getUnitPrice().multiply(new BigDecimal(update.getQuantity())));
            update.setUpdateTime(TimeUtils.now());
            this.updateSelectiveById(update);
            return update.getListingId();

        }
    }

    @Override
    public List<ListingDetailVo> checkAndFind(Long buyerId) {
        List<ServiceProductListing> serviceProductListingList = this.findByBuyerId(buyerId);
        if (serviceProductListingList == null) {
            return Collections.EMPTY_LIST;
        }
        this.checkLeaseListing(serviceProductListingList,0);

        List<ListingDetailVo> listingDetailVoList = new ArrayList<>(serviceProductListingList.size());
        for (ServiceProductListing serviceProductListing : serviceProductListingList) {
            ListingDetailVo listingDetailVo=new ListingDetailVo();
            //listingDetailVo.setServiceProduct(s);
            BeanUtils.copyProperties(listingDetailVo,serviceProductListing);
            if (serviceProductListing.getType() == 2) {//租赁填充信息
                List<Long> personLeaseIds = Utils.toLongIds(serviceProductListing.getPersonLeaseIds());
                List<PersonLeaseMessage> personLeaseMessageList=personLeaseMessageService.findByIds(personLeaseIds);
                listingDetailVo.setPersonLeaseMessageList(personLeaseMessageList);
                List<PersonLeaseMessage> confictList=new ArrayList<PersonLeaseMessage>();
                for (PersonLeaseMessage personLeaseMessage:personLeaseMessageList){
                    String confictIds=personLeaseMessage.getConfictIds();
                    if (StringUtils.isNotEmpty(confictIds)){
                        List<PersonLeaseMessage> temp=personLeaseMessageService.findByIds(Utils.toLongIds(confictIds));
                        temp=personLeaseMessageService.changeTimeDesc(personLeaseMessage,temp);
                        confictList.addAll(temp);
                    }
                }
                listingDetailVo.setConflictList(confictList);
            }
            listingDetailVoList.add(listingDetailVo);
        }


        return listingDetailVoList;
    }

    @Override
    @Transactional
    public Long addLeaseToListing(Integer check,SysUser user, Long productId, List<PersonLeaseMessage> personLeaseMessageList,Integer createOrAdd) {
        ServiceProduct serviceProduct = serviceProductService.findById(productId);
        if (serviceProduct == null || serviceProduct.getStatus() == 0) {
            throw new BusException("出租信息不存在或者已下架");
        }
       /* if (serviceProduct.getSellerId().equals(user.getUserId())){
            throw new BusException("不可租赁自己的出租信息");
        }*/


        personLeaseMessageList=personLeaseMessageService.addOrBuyPersonLeaseMessage(check,1,user,personLeaseMessageList,serviceProduct,null);


        ServiceProductListing serviceProductListing=new ServiceProductListing();
        BeanUtils.copyProperties(serviceProductListing,serviceProduct);
        serviceProductListing.setBuyerId(user.getUserId());
        serviceProductListing.setBuyerName(user.getUsername());
        serviceProductListing.setBuyerPhoneNo(user.getPhoneNo());
        // serviceProductListing.setLeaseId(leaseId);

        String personLeaseIds= StringUtils.join( BeanUtils.toList(personLeaseMessageList,"personLeaseId"),",");
        serviceProductListing.setPersonLeaseIds(personLeaseIds);
        BigDecimal totalPrice=BigDecimal.ZERO;
        for (PersonLeaseMessage personLeaseMessage:personLeaseMessageList){
            totalPrice=totalPrice.add(personLeaseMessage.getTotalPrice());
        }
        serviceProductListing.setTotalPrice(totalPrice);
        serviceProductListing.setEffectiveness(1);
        serviceProductListing.setUpdateTime(TimeUtils.now());
        ServiceProductListing serviceProductListingVo=this.findByBuyIdAndProduct(user.getUserId(),serviceProduct.getProductId());
        if (serviceProductListingVo==null || createOrAdd==0){
            serviceProductListing.setCreateTime(TimeUtils.now());
            insertSelective(serviceProductListing);
        }else{
            serviceProductListing.setTotalPrice(serviceProductListing.getTotalPrice().add(serviceProductListingVo.getTotalPrice()));
            serviceProductListing.setPersonLeaseIds(serviceProductListingVo.getPersonLeaseIds()+","+serviceProductListing.getPersonLeaseIds());
            serviceProductListing.setListingId(serviceProductListingVo.getListingId());
            this.updateSelectiveById(serviceProductListing);
        }

        return serviceProductListing.getListingId();
    }

    @Override
    public ServiceProductListing findByBuyIdAndProduct(Long buyId, Long productId) {
        Example<ServiceProductListing> example=ServiceProductListing.createExample();
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("buyerId",buyId);
        criteria.andEqualTo("productId",productId);
        criteria.andEqualTo("effectiveness",1);
        ServiceProductListing serviceProductListingVo=this.findOneByExample(example);
        return  serviceProductListingVo;
    }

    @Override
    public void updateListingQuantity(Long listingId, int quantity) {
        if (quantity <= 0) {
            throw new BusException("修改的数量必须大于0");
        }
        ServiceProductListing serviceProductListing = this.findById(listingId);
        if (serviceProductListing==null || serviceProductListing.getProductId()==null){
            throw  new BusException("购物车不存在或者已被删除");
        }
        ServiceProduct serviceProduct=serviceProductService.findById(serviceProductListing.getProductId());
        if (serviceProduct==null || serviceProduct.getStatus()==0){
            throw new BusException("该供应已被删除或下架");
        }
        if (serviceProduct.getInventory()<quantity){
            throw new BusException("添加的数量大于商品的库存");
        }
        if (serviceProductListing==null){
            throw new BusException("该清单不存在或已删除");
        }


        ServiceProductListing serviceProductListingVo=new ServiceProductListing();
        serviceProductListingVo.setListingId(serviceProductListing.getListingId());
        serviceProductListingVo.setQuantity(quantity);
        serviceProductListingVo.setTotalPrice(serviceProductListing.getUnitPrice().multiply(new BigDecimal(quantity)));
        this.updateSelectiveById(serviceProductListingVo);
    }

    @Override
    @Transactional
    public void deleteListingByIds(List<Long> listingIds,Integer way) {
        List<ServiceProductListing>  serviceProductListingList=this.findByIds(listingIds);
        List<String> personMessageIdString= BeanUtils.toList(serviceProductListingList,"personLeaseIds");
        String str=StringUtils.join(personMessageIdString,",");
        List<Long> personMessageIdList= Utils.toLongIds(str);
        if (way==0 && personMessageIdList!=null && personMessageIdList.size()>0){
            personLeaseMessageService.deleteBatchIds(personMessageIdList);
        }

        this.deleteBatchIds(listingIds);
    }

    @Override
    public List<ServiceProductListing> findByBuyerId(Long buyerId) {
        Example<ServiceProductListing> example=ServiceProductListing.createExample();
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("buyerId",buyerId);
        example.orderBy("type");
        example.orderBy("createTime");
        return this.findListByExample(example);
    }

    @Override
    public Long countByBuyerId(Long buyerId) {
        Example<ServiceProductListing> example=ServiceProductListing.createExample();
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("buyerId",buyerId);
        return countByExample(example);
    }

    @Override
    public void updateEffectiveness(Long productId, Integer effectiveness, String failureReason) {
        Example<ServiceProductListing> example=ServiceProductListing.createExample();
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("productId",productId);
        ServiceProductListing serviceProductListing=new ServiceProductListing();
        serviceProductListing.setEffectiveness(effectiveness);
        serviceProductListing.setFailureReason(failureReason);
        updateSelectiveByExample(serviceProductListing,example);
    }

    @Override
    public void updateEffectivenessById(Long listingId, Integer effectiveness, String failureReason) {
        ServiceProductListing serviceProductListing=new ServiceProductListing();
        serviceProductListing.setListingId(listingId);
        serviceProductListing.setEffectiveness(effectiveness);
        serviceProductListing.setFailureReason(failureReason);
        updateSelectiveById(serviceProductListing);
    }

    @Override
    public void checkLeaseListingByIds(List<Long> listingIds,Integer deleteListing) {
        List<ServiceProductListing> serviceProductListingList=this.findByIds(listingIds);
        this.checkLeaseListing(serviceProductListingList,deleteListing);
    }

    @Override
    @Transactional
    public void checkLeaseListing(List<ServiceProductListing> serviceProductListingList, Integer deleteListing) {
        for (ServiceProductListing serviceProductListing:serviceProductListingList) {
            if (serviceProductListing.getEffectiveness()==0){
                continue;
            }
            ServiceProduct serviceProduct = serviceProductService.findById(serviceProductListing.getProductId());
            if (serviceProductListing.getType() == 2) {
                if(serviceProduct==null || serviceProduct.getStatus()==0 || serviceProductListing.getUpdateTime().getTime()<serviceProduct.getUpdateTime().getTime()){
                    this.updateEffectivenessById(serviceProductListing.getListingId(), 0, serviceProductListing.getProductName() + "课室信息发生变动，购物车失效");
                }
                String personLeaseIds=serviceProductListing.getPersonLeaseIds();
                if (StringUtils.isNotEmpty(personLeaseIds)){
                    List<PersonLeaseMessage> personLeaseMessageList=personLeaseMessageService.findByIds(Utils.toLongIds(personLeaseIds));
                    for (PersonLeaseMessage personLeaseMessage:personLeaseMessageList){
                        String conflictIds=personLeaseMessage.getConfictIds()==null?"":personLeaseMessage.getConfictIds();
                        PersonLeaseQueryVo personLeaseQueryVo = new PersonLeaseQueryVo();
                        personLeaseQueryVo.setProductId(serviceProduct.getProductId());
                        //personLeaseQueryVo.setRoomId(serviceProduct.getRoomId());
                        personLeaseQueryVo.setEndTimeGreateStartTime(personLeaseMessage.getEndTime());
                        personLeaseQueryVo.setStartTimeLessEndTime(personLeaseMessage.getStartTime());
                        personLeaseQueryVo.setStartLessEnd(personLeaseMessage.getStart());
                        personLeaseQueryVo.setEndGreateStart(personLeaseMessage.getEnd());
                        //personLeaseQueryVo.setWeekNum(personLeaseSearchVo.getWeekNum());
                        personLeaseQueryVo.setLeaseStates("0,1");
                        personLeaseQueryVo.setOrderByStart("yes");
                        List<PersonLeaseMessage> checkPersonLeaseMessageList = personLeaseMessageService.findPersonLeaseMessage(personLeaseQueryVo);
                        PersonLeaseQueryVo newPersonLeaseQueryVo = new PersonLeaseQueryVo();
                        newPersonLeaseQueryVo.setRoomId(serviceProduct.getRoomId());
                        newPersonLeaseQueryVo.setEndTimeGreateStartTime(personLeaseMessage.getEndTime());
                        newPersonLeaseQueryVo.setStartTimeLessEndTime(personLeaseMessage.getStartTime());
                        newPersonLeaseQueryVo.setStartLessEnd(personLeaseMessage.getStart());
                        newPersonLeaseQueryVo.setEndGreateStart(personLeaseMessage.getEnd());
                        newPersonLeaseQueryVo.setLeaseState(999);
                        newPersonLeaseQueryVo.setOrderByStart("yes");
                        List<PersonLeaseMessage> hasUsePersonLeaseMessageList = personLeaseMessageService.findPersonLeaseMessage(newPersonLeaseQueryVo);
                        if (hasUsePersonLeaseMessageList!=null && hasUsePersonLeaseMessageList.size()>0){
                            checkPersonLeaseMessageList.addAll(hasUsePersonLeaseMessageList);
                        }
                        Iterator<PersonLeaseMessage> iterator=checkPersonLeaseMessageList.iterator();
                        while (iterator.hasNext()){
                            PersonLeaseMessage checkPersonLeaseMessage=iterator.next();
                            if (personLeaseMessage.getWeekNum()!=null && checkPersonLeaseMessage.getWeekNum()!=null && personLeaseMessage.getWeekNum()!=-1 && checkPersonLeaseMessage.getWeekNum()!=-1 && !personLeaseMessage.getWeekNum().equals(checkPersonLeaseMessage.getWeekNum())){
                                iterator.remove();
                            }
                        }
                        String checkConflictIds = StringUtils.join(BeanUtils.toList(checkPersonLeaseMessageList, "personLeaseId"), ",");
                        if (!conflictIds.equals(checkConflictIds)) {
                            this.updateEffectivenessById(serviceProductListing.getListingId(), 0, serviceProductListing.getProductName() + "课室信息发生变动，购物车失效");
                        }
                    }
                }
                if (deleteListing == 1) {
                    this.deleteById(serviceProductListing.getListingId());
                    if (StringUtils.isNotEmpty(personLeaseIds)){
                        personLeaseMessageService.deleteBatchIds(Utils.toLongIds(personLeaseIds));
                    }
                }
            } else {
                if (serviceProduct==null || !serviceProductListing.getUnitPrice().equals(serviceProduct.getUnitPrice()) || serviceProduct.getStatus()==0) {
                    this.updateEffectivenessById(serviceProductListing.getListingId(), 0, serviceProductListing.getProductName() + "供应信息发生变动，购物车失效");
                    if (deleteListing == 1) {
                        this.deleteById(serviceProductListing.getListingId());
                    }
                }
            }
        }
    }
}